import re
import json


def read_sql_file(file_path):
    with open(file_path, 'r', encoding='utf-8') as file:
        sql_content = file.read()
    return sql_content


def split_sql_statements(sql_content):
    # 使用正则表达式分割SQL语句
    delimiter = r'\n\s*\n'
    statements = re.split(delimiter, sql_content)
    return [stmt.strip() for stmt in statements if stmt.strip()]


def create_ddl_json(statements):
    ddl_jsons = []
    for stmt in statements:
        ddl_jsons.append({"ddl": stmt})
    return ddl_jsons


def main():
    # 假设您的SQL文件名为 'example.sql'
    file_path = './data/create_ddl_2.sql'

    # 读取SQL文件内容
    sql_content = read_sql_file(file_path)

    # 分割SQL语句
    statements = split_sql_statements(sql_content)

    # 创建DDL JSON对象列表
    ddl_jsons = create_ddl_json(statements)

    # 输出或保存JSON对象
    for ddl_json in ddl_jsons:
        print(json.dumps(ddl_json, ensure_ascii=False, indent=2))

    # 如果需要保存到文件
    with open('./data/smartpole_ddl_2.json', 'w', encoding='utf-8') as output_file:
        json.dump(ddl_jsons, output_file, ensure_ascii=False, indent=2)


if __name__ == "__main__":
    main()